﻿using System;
using System.ComponentModel.Composition;
using System.ServiceModel;
using OrbitOne.CRMLyncInfoDashboard.CRM.Organization;

namespace OrbitOne.CRMLyncInfoDashboard.CRM.WCF
{
    [Export(typeof(IWCFHelper))]
    public class WCFHelper : IWCFHelper
    {
       

        public IOrganizationService GetConnection(Uri serverUrl)
        {
            var serviceUrl = CombineUrl(serverUrl, "/XRMServices/2011/Organization.svc/web");

            var binding = new BasicHttpBinding((Uri.UriSchemeHttps == serviceUrl.Scheme)
                                                   ? BasicHttpSecurityMode.Transport
                                                   : BasicHttpSecurityMode.TransportCredentialOnly)
                              {
                                  MaxReceivedMessageSize = int.MaxValue,
                                  MaxBufferSize = int.MaxValue,
                                  SendTimeout = TimeSpan.FromMinutes(2)
                              };
            return new OrganizationServiceClient(binding, new EndpointAddress(serviceUrl));
        }

        public static Uri CombineUrl(Uri baseValue, string value)
        {
            if (null == baseValue)
            {
                throw new ArgumentNullException("baseValue");
            }
            if (string.IsNullOrEmpty(value))
            {
                return baseValue;
            }

            //Ensure that a double '/' is not being added
            var newValue = baseValue.AbsoluteUri;
            if (!newValue.EndsWith("/", StringComparison.Ordinal))
            {
                //Check if there is a character at the beginning of value
                if (!value.StartsWith("/", StringComparison.Ordinal))
                {
                    newValue += "/";
                }
            }
            else if (value.StartsWith("/", StringComparison.Ordinal))
            {
                value = value.Substring(1);
            }

            //Create the combined URL
            return new Uri(newValue + value);
        }
    }
}
